package com.samoiloff.framework {
	import com.samoiloff.framework.controller.AbstractController;
	import com.samoiloff.framework.model.AbstractModel;
	import com.samoiloff.framework.model.BaseModel;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	/**
	 * @author Samoiloff
	 */
	public class ComponentBase extends EventDispatcher {
		
		protected var _model		: BaseModel;
		protected var _controller	: AbstractController;

		public function ComponentBase() {
			
			var modelCls:Class = getModelClass();
			_model = new modelCls(this) as BaseModel;
			
			if (_model.ready) {
				onModelComplete();
			} else {
				_model.addEventListener(Event.COMPLETE, onModelComplete);
			}
		}

		private function onModelComplete(e:Event = null):void {
			_model.removeEventListener(Event.COMPLETE, onModelComplete);
			
			var controllerCls:Class = getControllerCls();
			_controller = new controllerCls(_model) as AbstractController;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function get ready():Boolean {
			return _model.ready;
		}

		public function destroy():void {
			if (_controller) {
				_controller.destroy();
				_controller = null;
			}
			
			if (_model) {
				_model.removeEventListener(Event.COMPLETE, onModelComplete);
				_model.destroy();
				_model = null;
			}
		}
		
		protected function getModelClass():Class {
			return AbstractModel;
		}
		
		protected function getControllerCls():Class {
			return AbstractController;
		}
		
	}
}
